package com.lambkit.plugin.smarthttp.http;

import com.lambkit.core.Attr;
import com.lambkit.core.Lambkit;
import com.lambkit.core.http.*;
import com.lambkit.core.task.http.HttpWorkCenter;
import com.lambkit.web.HttpContextHolder;
import org.smartboot.http.common.Cookie;
import org.smartboot.http.server.HttpRequest;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Enumeration;
import java.util.Map;

/**
 * @author yangyong(孤竹行)
 */
public class SmartHttpRequest implements IRequest {

    private HttpRequest request;

    private Attr attributes = new Attr();

    private String rawData;

    private SmartHttpSession session;

    public SmartHttpRequest(HttpRequest request) {
        this.request = request;
    }

    @Override
    public Object getSource() {
        return request;
    }

    @Override
    public Enumeration<String> getAttributeNames() {
        return new ArrayEnumeration(attributes.getAttrNames());
    }

    @Override
    public <T> T getAttribute(String name) {
        return attributes.get(name);
    }

    @Override
    public Map<String, Object> getAttributeMap() {
        return attributes;
    }

    @Override
    public void setAttribute(String name, Object value) {
        attributes.set(name, value);
    }

    @Override
    public void removeAttribute(String name) {
        attributes.remove(name);
    }

    @Override
    public String getRawData() {
        if(rawData != null) {
            return rawData;
        }
        StringBuilder sb = new StringBuilder();
        InputStream inputStream = null;
        BufferedReader reader = null;
        try {
            inputStream = request.getInputStream();
            reader = new BufferedReader(new InputStreamReader(inputStream, Charset.forName("UTF-8")));
            String line = "";
            while ((line = reader.readLine()) != null) {
                sb.append(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (inputStream != null) {
                try {
                    inputStream.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
            if (reader != null) {
                try {
                    reader.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        rawData = sb.toString();
        return rawData;
    }

    @Override
    public String getParameter(String name) {
        return request.getParameter(name);
    }

    @Override
    public Map<String, String[]> getParameterMap() {
        return request.getParameters();
    }

    @Override
    public Enumeration<String> getParameterNames() {
        return new SetEnumeration(request.getParameters().keySet());
    }

    @Override
    public String[] getParameterValues(String name) {
        return request.getParameterValues(name);
    }

    @Override
    public String getHeader(String name) {
        return request.getHeader(name);
    }

    @Override
    public ISession getSession(boolean create) {
        if(session == null && create) {
            session = new SmartHttpSession();
        }
        return session;
    }

    @Override
    public ICookie[] getCookies() {
        Cookie[] cookies = request.getCookies();
        SmartHttpCookie[] smartHttpCookies = new SmartHttpCookie[cookies.length];
        for(int i = 0; i < cookies.length; i++) {
            smartHttpCookies[i] = new SmartHttpCookie(cookies[i]);
        }
        return smartHttpCookies;
    }

    @Override
    public String getMethod() {
        return request.getMethod();
    }

    @Override
    public String getRequestURI() {
        return request.getRequestURI();
    }

    @Override
    public String getRequestURL() {
        return request.getRequestURL();
    }

    @Override
    public void forward(String path, IResponse response) {
        HttpWorkCenter workCenter = Lambkit.app().context().getWorkCenter(HttpWorkCenter.class);
        IHttpContext context = HttpContextHolder.get();
        context.setTarget(path);
        workCenter.handle(context);
    }

    @Override
    public String getRemoteAddr() {
        return request.getRemoteAddr();
    }

    @Override
    public String getScheme() {
        return request.getScheme();
    }

    @Override
    public String getServerName() {
        String host = getHeader("Host");
        if (host == null || "".equals(host.trim())) {
            host = request.getLocalAddress().getHostString();
        } else {
            if (host.startsWith("[")) {
                host = host.substring(1, host.indexOf(']'));
            } else if (host.indexOf(':') != -1) {
                host = host.substring(0, host.indexOf(':'));
            }
        }
        return host;
    }

    @Override
    public int getServerPort() {
        String host = getHeader("Host");
        if (host != null) {
            //for ipv6 addresses we make sure we take out the first part, which can have multiple occurrences of :
            final int colonIndex;
            if (host.startsWith("[")) {
                colonIndex = host.indexOf(':', host.indexOf(']'));
            } else {
                colonIndex = host.indexOf(':');
            }
            if (colonIndex != -1) {
                try {
                    return Integer.parseInt(host.substring(colonIndex + 1));
                } catch (NumberFormatException ignore) {}
            }
            if (getScheme().equals("https")) {
                return 443;
            } else if (getScheme().equals("http")) {
                return 80;
            }
        }
        return request.getLocalAddress().getPort();
    }

    @Override
    public BufferedReader getReader() throws IOException {
        InputStreamReader isr = new InputStreamReader(request.getInputStream());
        return new BufferedReader(isr);
    }

    @Override
    public String getContentType() {
        return request.getContentType();
    }

    @Override
    public String getQueryString() {
        return request.getQueryString();
    }
}
